package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.config.CacheService;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.message.ArticleConstans;
import com.heima.feigns.admin.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.HotArticleVo;
import com.heima.model.article.pojos.ApArticle;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {


    @Autowired
    ApArticleMapper apArticleMapper;

    /**
     * 计算热文章
     */
    @Override
    public void computeHotArticle() {
        //1 查询前5天的文章（未删除\未下架的所有文章）
        // 如何得到前5天时间？ 日期加减运算
        String date = DateTime.now().minusDays(5).toString("yyyy-MM-dd 00:00:00");
        List<ApArticle> articleList = apArticleMapper.selectList(Wrappers.<ApArticle>lambdaQuery()
                .gt(ApArticle::getPublishTime, date));
        if (articleList == null || articleList.size() == 0) {
            log.info("articleList is null");
            return;
        }

        //2 计算文章的分值
       List<HotArticleVo> hotArticleVos = computeArticleScore(articleList);


        //3 缓存热点文章
        cacheTagToRedis(hotArticleVos);

    }

    @Autowired
    AdminFeign adminFeign;

    /**
     * 缓存热点文章
     * @param hotArticleVos
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVos) {

        //1 查询所有的频道
        List<AdChannel> channelList = adminFeign.findAllChannels();

        //3 缓存对应频道下的热点文章
        channelList.forEach( adChannel -> {

//            hotArticleVos.forEach( hotArticleVo -> {
//                if (hotArticleVo.getChannelId().intValue() == adChannel.getId().intValue()) {
//                    // 当前文章属于当前频道
//                }
//            });
            List<HotArticleVo> channelHotList  = hotArticleVos.stream()
                    .filter( hotArticleVo -> hotArticleVo.getChannelId().intValue() == adChannel.getId().intValue() )
                    .collect(Collectors.toList());
            // 对应频道下的文章
            sortAndCache(channelHotList, ArticleConstans.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
        });


        //4 缓存推荐下的热点文章（所有文章的前30）
        sortAndCache(hotArticleVos, ArticleConstans.HOT_ARTICLE_FIRST_PAGE + ArticleConstans.DEFAULT_TAG);
    }

    @Autowired
    CacheService cacheService;

    /**
     * 执行保存热点文章到Redis 并排序   前30条
     * @param hotArticleVos  带分值文章列表
     * @param key 缓存到redis key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        // 排序
        hotArticleVos =hotArticleVos.stream()
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                        .limit(30)
                        .collect(Collectors.toList());
        // 保存到redis
        cacheService.set(key, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 2 计算文章分值
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> articleList) {
//        articleList.stream().map()

        List<HotArticleVo> hotArticleVos = new ArrayList<>();

        for (ApArticle apArticle : articleList) {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, hotArticleVo);
            // 计算分数
            int score = apArticlecomputeScore(apArticle);
            hotArticleVo.setScore(score);

            hotArticleVos.add(hotArticleVo);
        }
        return hotArticleVos;
    }

    /**
     * 计算文章分数
     * （阅读：1，点赞：3，评论：5，收藏：8）
     * @param apArticle
     * @return
     */
    private int apArticlecomputeScore(ApArticle apArticle) {

        int score = 0;
        //阅读
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * ArticleConstans.HOT_ARTICLE_VIEW_WEIGHT;
        }

        //点赞
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstans.HOT_ARTICLE_LIKE_WEIGHT;
        }

        // 评论 5
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstans.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 收藏 8
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstans.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
